package guzb.cnblogs.security.quickdemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

import java.util.ArrayList;
import java.util.List;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration
@EnableWebSecurity
public class WebSecuritySetting {

    /** 权限配置 */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                .authorizeHttpRequests((auth) -> {
                    auth.antMatchers("/", "/index").permitAll()
                            .antMatchers("/books").authenticated()
                            .antMatchers("/system").hasRole("ADMIN");
                })
                .formLogin(withDefaults()).httpBasic()
                .and()
                .logout().deleteCookies("remove")
                .invalidateHttpSession(true).logoutUrl("/logout");
        return httpSecurity.build();
    }

    /**
     * 提供一个默认的密码加密器
     */
    @Bean
    public PasswordEncoder createPasswordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    /** 基于内存的用户信息服务 */
    @Bean
    public UserDetailsService userDetailsService() {
        List<UserDetails> users = new ArrayList<>(2);
        UserDetails user = User.withDefaultPasswordEncoder()
                .username("user")
                .password("codefate")
                .roles("USER")
                .build();

        users.add(user);

        user = User.withDefaultPasswordEncoder()
                .username("admin")
                .password("codefate")
                .roles("ADMIN")
                .build();
        users.add(user);

        return new InMemoryUserDetailsManager(users);
    }

}
